#pragma once

#include <iostream>
#include "Protocal.hpp"

enum
{
    DIV_ZERO = 1,
    MOD_ZERO,
    OTHER_OPER
};

class ServerCal
{
public:
    // "len"\n"10 + 20"\n
    // 解释 --> 计算
    std::string Calculator(std::string &package)
    {
        std::string content;
        bool r = Decode(package, &content);     // struct
        if (!r)
            return "";

        // "10 + 20"
        Request req;
        r = req.Deserialize(content);   // 反序列化：req内：x=10 y=20
        if (!r)
            return "";
        content = "";

        // 开始计算， 并将计算的得到的结果 构建成响应，给我响应回来
        Response resp = CalculatorHelper(req); // result=30 code=0
        resp.Serialize(&content);   // 序列化：转成 string
        content = Encode(content);  // 再转成可以在网络上发送的 string

        return content;
    }

private:
    Response CalculatorHelper(const Request &req)
    {
        Response resp(0, 0);
        switch (req.op)
        {
        case '+':
            resp.result = req.x + req.y;
            break;
        case '-':
            resp.result = req.x - req.y;
            break;
        case '*':
            resp.result = req.x * req.y;
            break;
        case '/':
        {
            if (req.y == 0)
                resp.code = DIV_ZERO;
            else
                resp.result = req.x / req.y;
        }
        break;
        case '%':
        {
            if (req.y == 0)
                resp.code = MOD_ZERO;
            else
                resp.result = req.x % req.y;
        }
        break;
        default:
            resp.code = OTHER_OPER;
            break;
        }

        return resp;
    }
};
